<template>
    <!-- vue实例外创建 -->
    <div>
      <div class="login">
        <h1>登录</h1>
        <el-form ref="loginform" :rules="rules" :model="form" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input placeholder="请输入用户名" v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input placeholder="请输入密码" v-model="form.password" show-password></el-input>
          </el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form>
      </div>
    </div>
  </template>
  
  <script>
 import { Login } from '@/api/user';
  export default {
    data() {
      return {
          form: {
            username: '',
            password:''
          },
          rules: {
              username: [
              { required: true, message: '请输入用户名', trigger: 'change' },
           
            ],
            password:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            ]
            
          }
      }
    },
    methods:{
      login(){
          // 前置拦截
          this.$refs['loginform'].validate(async(valid)=>{
             if (valid) {
              // 前置验证通过后执行代码
              console.log(this.form);

              //发起请求
              //发起一个post请求              将接口替换成封装好的Login 并且将this.form传值
              let {data,meta} =  await Login(this.form)
              console.log(data,meta) 
            
            // 什么时候跳转？--有token的时候
            if(meta.status!==200) return this.$message.error(meta.msg)
            localStorage.setItem('admin_token',data.token)

          this.$router.push('/')
            }
          })
      },
    }
  };
  </script>
  
  <style scoped>
  .login {
    width: 400px;
    height: 400px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border: 1px solid;
    border-radius: 15px;
    padding: 20px;
    box-sizing: border-box;
    text-align: center;
  }
  h1 {
    text-align: center;
  }
  </style>
  